package forms;

import DAO.CategoriasDAO;
import DAO.ProdutoDAO;
import DAO.UnidadeMedidaDAO;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import model.Categorias;
import model.Produto;
import model.UnidadeMedida;

public class frmProdutos extends javax.swing.JFrame {

    List<Categorias> lsCat;
    List<UnidadeMedida> lsUnm;
    boolean alterar = false;

    public frmProdutos() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        TabPai = new javax.swing.JTabbedPane();
        TabListagem = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabProduto = new javax.swing.JTable();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel17 = new javax.swing.JLabel();
        txtFiltroNome = new javax.swing.JTextField();
        btnDeletar = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        btnNovo = new javax.swing.JButton();
        btnBuscar = new javax.swing.JButton();
        TabCadastro = new javax.swing.JPanel();
        btnSalvar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        txtQntMin = new javax.swing.JTextField();
        txtNome = new javax.swing.JTextField();
        comboboxCategoria = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txtPreco = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtDescricao = new javax.swing.JTextField();
        txtQnt = new javax.swing.JTextField();
        txtDataCadastro = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        cbxUnidadeMedida = new javax.swing.JComboBox();
        radAtivo = new javax.swing.JRadioButton();
        radInativo = new javax.swing.JRadioButton();
        jLabel10 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        lblCodigo = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        TabPai.setPreferredSize(new java.awt.Dimension(700, 600));

        TabListagem.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        tabProduto.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Código:", "Nome:", "Preço:", "Status:", "Quantidade"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tabProduto);

        TabListagem.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, 780, 256));
        TabListagem.add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 60, 800, 10));

        jLabel17.setText("Nome:");
        TabListagem.add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
        TabListagem.add(txtFiltroNome, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 236, -1));

        btnDeletar.setText("Deletar");
        btnDeletar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeletarActionPerformed(evt);
            }
        });
        TabListagem.add(btnDeletar, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 330, 140, -1));

        btnAlterar.setText("Alterar");
        btnAlterar.setPreferredSize(new java.awt.Dimension(57, 23));
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });
        TabListagem.add(btnAlterar, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 330, 135, -1));

        btnNovo.setText("Novo");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });
        TabListagem.add(btnNovo, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 330, 135, -1));

        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });
        TabListagem.add(btnBuscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(690, 10, -1, 40));

        TabPai.addTab("Listagem", TabListagem);

        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jLabel2.setText("Nome:");

        jLabel11.setText("Quantidade:");

        comboboxCategoria.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel4.setText("Descrição:");

        jLabel5.setText("Preço:");

        jLabel7.setText("UM:");

        jLabel6.setText("Data:");

        txtDataCadastro.setEnabled(false);

        jLabel8.setText("Status:");

        cbxUnidadeMedida.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        buttonGroup1.add(radAtivo);
        radAtivo.setText("Ativo");

        buttonGroup1.add(radInativo);
        radInativo.setText("Inativo");

        jLabel10.setText("Qtde. Mín:");

        jLabel9.setText("Categoria:");

        lblCodigo.setText("0");

        javax.swing.GroupLayout TabCadastroLayout = new javax.swing.GroupLayout(TabCadastro);
        TabCadastro.setLayout(TabCadastroLayout);
        TabCadastroLayout.setHorizontalGroup(
            TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(TabCadastroLayout.createSequentialGroup()
                .addComponent(lblCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(TabCadastroLayout.createSequentialGroup()
                .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(TabCadastroLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(TabCadastroLayout.createSequentialGroup()
                                .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addGroup(TabCadastroLayout.createSequentialGroup()
                                            .addGap(9, 9, 9)
                                            .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                                .addComponent(jLabel7)
                                                .addComponent(jLabel2))))
                                    .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtDescricao)
                                    .addComponent(txtNome)
                                    .addGroup(TabCadastroLayout.createSequentialGroup()
                                        .addComponent(txtPreco, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabel6)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtDataCadastro, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jLabel10)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtQntMin, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabel11)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(txtQnt, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addGroup(TabCadastroLayout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(comboboxCategoria, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, TabCadastroLayout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(TabCadastroLayout.createSequentialGroup()
                        .addGap(72, 72, 72)
                        .addComponent(cbxUnidadeMedida, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(TabCadastroLayout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(radAtivo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(radInativo)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        TabCadastroLayout.setVerticalGroup(
            TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(TabCadastroLayout.createSequentialGroup()
                .addComponent(lblCodigo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbxUnidadeMedida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtPreco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtDataCadastro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(jLabel10)
                    .addComponent(txtQntMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11)
                    .addComponent(txtQnt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboboxCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addGap(12, 12, 12)
                .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radInativo)
                    .addComponent(radAtivo)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(TabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnSalvar))
                .addContainerGap(123, Short.MAX_VALUE))
        );

        TabPai.addTab("Cadastro", TabCadastro);

        jMenu1.setText("Fechar");
        jMenu1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu1MouseClicked(evt);
            }
        });
        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(TabPai, javax.swing.GroupLayout.PREFERRED_SIZE, 800, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(11, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(TabPai, javax.swing.GroupLayout.PREFERRED_SIZE, 404, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(56, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        if (txtNome.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Campo Nome do Produto É Necessário!");
            txtNome.requestFocus();
        } else if (txtPreco.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Campo Preço É Necessário!");
            txtPreco.requestFocus();
        } else if (txtQnt.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Campo Quantidade É Necessário!");
            txtQnt.requestFocus();
        } else if (txtQntMin.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Campo Quantidade Mínima É Necessário!");
            txtQntMin.requestFocus();
        } else if (Double.parseDouble(txtQntMin.getText()) > Double.parseDouble(txtQnt.getText())) {
            JOptionPane.showMessageDialog(this, "Quantidade Deve Ser Maior ou Igual a Quantidade Mínima");
            txtQntMin.requestFocus();
        } else {
            try {
                int PRD_ID = Integer.parseInt(lblCodigo.getText());
                int CTG_ID = lsCat.get(comboboxCategoria.getSelectedIndex()).getCodigo();
                int UNM_ID = lsUnm.get(cbxUnidadeMedida.getSelectedIndex()).getCodigo();
                String PRD_NOME = (txtNome.getText());
                String PRD_DESCRICAO = (txtDescricao.getText());
                Double PRD_PRECO = Double.parseDouble(txtPreco.getText());
                boolean PRD_STATUS;
                if (radAtivo.isSelected()) {
                    PRD_STATUS = true;
                } else {
                    PRD_STATUS = false;
                }
                Double PRD_QUANTIDADEMINIMA = Double.parseDouble(txtQntMin.getText());
                Double PRD_QUANTIDADE = Double.parseDouble(txtQnt.getText());

                Produto prod = new Produto();
                prod.setCodigo(PRD_ID);
                Categorias categ = new Categorias();
                categ.setCodigo(CTG_ID);
                prod.setCategoria(categ);
                UnidadeMedida unid = new UnidadeMedida();
                unid.setCodigo(UNM_ID);
                prod.setUnidadeMedida(unid);
                prod.setNome(PRD_NOME);
                prod.setDescricao(PRD_DESCRICAO);
                prod.setPreco(PRD_PRECO);
                prod.setStatus(PRD_STATUS);
                prod.setQuantidadeMinima(PRD_QUANTIDADEMINIMA);
                prod.setQuantidade(PRD_QUANTIDADE);
                ProdutoDAO dao = new ProdutoDAO();
                if (alterar == false) {
                    prod.setDataCadastro(new Date());
                    dao.insert(prod);
                    JOptionPane.showMessageDialog(this, "Protudo Salvo!");
                } else {
                    dao.update(prod);
                    JOptionPane.showMessageDialog(this, "Produto Alterado!");
                }
                              
                
                
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Produto não pode ser alterado");
            }

            txtNome.setText("");
            txtDescricao.setText("");
            txtPreco.setText("");
            txtQntMin.setText("");
            txtQnt.setText("");

            TabPai.setSelectedIndex(0);
            atualizagrid();
        }
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void btnDeletarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeletarActionPerformed
        String codigo = "" + tabProduto.getValueAt(tabProduto.getSelectedRow(), 0);
        try {
            ProdutoDAO DAO = new ProdutoDAO();
            DAO.delete(Integer.parseInt(codigo));
            atualizagrid();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Produto não pode ser deletado, está sendo usado no Estoque!");
        }

    }//GEN-LAST:event_btnDeletarActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        alterar = true;

        String codigo = "" + tabProduto.getValueAt(tabProduto.getSelectedRow(), 0);
        try {
            ProdutoDAO DAO = new ProdutoDAO();
            Produto p = DAO.findByCodigo(Integer.parseInt(codigo));
            lblCodigo.setText(String.valueOf(p.getCodigo()));
            cbxUnidadeMedida.setSelectedItem(p.getUnidadeMedida().getNome());
            comboboxCategoria.setSelectedItem(p.getCategoria().getNome());
            txtNome.setText(p.getNome());
            txtDescricao.setText(p.getDescricao());
            txtPreco.setText(String.valueOf(p.getPreco()));
            txtQntMin.setText(String.valueOf(p.getQuantidadeMinima()));
            txtQnt.setText(String.valueOf(p.getQuantidade()));
            SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
            txtDataCadastro.setText(format.format(p.getDataCadastro()));
            if (p.isStatus()) {
                radAtivo.setSelected(true);
            } else {
                radInativo.setSelected(true);
            }
        } catch (Exception ex) {
            Logger.getLogger(frmProdutos.class.getName()).log(Level.SEVERE, null, ex);
        }
        TabPai.setSelectedIndex(1);
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        alterar = false;
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        txtDataCadastro.setText(format.format(new Date()));
        TabPai.setSelectedIndex(1);
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        DefaultTableModel modelo = (DefaultTableModel) tabProduto.getModel();
        modelo.setNumRows(0);
        try {
            ProdutoDAO dao = new ProdutoDAO();
            for (Produto p : dao.findByNome(txtFiltroNome.getText())) {

                modelo.addRow(
                        new String[]{
                            "" + p.getCodigo(),
                            p.getNome(),
                            "" + p.getPreco(),
                            p.isStatus() ? "Ativo" : "Inativo",
                            "" + p.getQuantidade()});
            }
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        lblCodigo.setVisible(false);
        radAtivo.setSelected(true);
        atualizagrid();
        try {
            CategoriasDAO dao = new CategoriasDAO();
            lsCat = dao.findAll();
            ArrayList<String> ls = new ArrayList<String>();
            for (Categorias c : lsCat) {
                ls.add(c.getNome());
            }
            comboboxCategoria.setModel(new javax.swing.DefaultComboBoxModel(ls.toArray()));
        } catch (Exception ex) {
            Logger.getLogger(frmProdutos.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            UnidadeMedidaDAO unmdao = new UnidadeMedidaDAO();
            lsUnm = unmdao.findAll();
            ArrayList<String> ls = new ArrayList<String>();
            for (UnidadeMedida u : lsUnm) {
                ls.add(u.getNome());
            }
            cbxUnidadeMedida.setModel(new javax.swing.DefaultComboBoxModel(ls.toArray()));
        } catch (Exception ex) {
            Logger.getLogger(frmProdutos.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_formWindowOpened

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        lblCodigo.setText("0");
        txtNome.setText("");
        txtDescricao.setText("");
        txtPreco.setText("");
        txtQntMin.setText("");
        txtQnt.setText("");
        TabPai.setSelectedIndex(0);
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void jMenu1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu1MouseClicked
this.dispose();
    }//GEN-LAST:event_jMenu1MouseClicked
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;


                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmProdutos.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmProdutos.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmProdutos.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmProdutos.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmProdutos().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel TabCadastro;
    private javax.swing.JPanel TabListagem;
    private javax.swing.JTabbedPane TabPai;
    private javax.swing.JButton btnAlterar;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnDeletar;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnSalvar;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JComboBox cbxUnidadeMedida;
    private javax.swing.JComboBox comboboxCategoria;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JRadioButton radAtivo;
    private javax.swing.JRadioButton radInativo;
    private javax.swing.JTable tabProduto;
    private javax.swing.JTextField txtDataCadastro;
    private javax.swing.JTextField txtDescricao;
    private javax.swing.JTextField txtFiltroNome;
    private javax.swing.JTextField txtNome;
    private javax.swing.JTextField txtPreco;
    private javax.swing.JTextField txtQnt;
    private javax.swing.JTextField txtQntMin;
    // End of variables declaration//GEN-END:variables

    private void atualizagrid() {
        DefaultTableModel modelo = (DefaultTableModel) tabProduto.getModel();
        modelo.setNumRows(0);
        try {
            ProdutoDAO dao = new ProdutoDAO();
            for (Produto p : dao.findGrid()) {

                modelo.addRow(
                        new String[]{
                            "" + p.getCodigo(),
                            p.getNome(),
                            "" + p.getPreco(),
                            p.isStatus() ? "Ativo" : "Inativo",
                            "" + p.getQuantidade()});
            }
        } catch (Exception ex) {
        }
    }
}
